package com.helsinki.mapper;

import com.helsinki.pojo.UserInfo;
import org.apache.ibatis.annotations.*;
import org.springframework.security.core.parameters.P;

import java.util.List;

public interface UserMapper {
    @Select("select * from users where username = #{username}")
    UserInfo findByUsername(String username);

    // 根据id查询用户详情 (将角色信息, 以及角色对应的权限信息 都查出来)
    @Select("select * from users where id = #{id}")
    @Results(id = "userinfo",value={
            @Result(id = true, property = "id", column = "id"),
            @Result(property = "username", column = "username"),
            @Result(property = "email", column = "email"),
            @Result(property = "password", column = "password"),
            @Result(property = "phoneNum", column = "phoneNum"),
            @Result(property = "status", column = "status"),
            // 根据用户id查角色列表
            @Result(property = "roles", column = "id",
                    many = @Many(select = "com.helsinki.mapper.RoleMapper.findByUid"))
    })
    UserInfo findById(String id);

    @Insert("insert into user_role(userId, roleId, id) values(#{userId}, #{roleId}, replace(uuid(), '-', ''))")
    int addRole(@Param("userId") String userId, @Param("roleId") String roleId);

    //添加用户
    @Insert("insert into users (id,email,username,password,phoneNum,status) " +
            "value(#{id},#{email},#{username},#{password},#{phoneNum},#{status})")
    void save(UserInfo user) throws Exception;

    //查询全部
    @Select("select * from users")
    List<UserInfo> findAll();

    //更新用户信息
    @Update("update users set " +
            "email = #{email}," +
            "username = #{username}, " +
            "password = #{password}, " +
            "phoneNum = #{phoneNum}," +
            "status = #{status} "  +
            "where id = #{id}")
    void updateUser(UserInfo userInfo);

    @Delete("delete from users_role where userId = #{id}")
    void deleteRoleByUId(String id);

    @Insert("insert into users_role (roleId, userId)" +
            "values(#{roleId},#{userId})")
    void insertRoleByUId(@Param("roleId") String rId,@Param("userId") String id);

    @Delete("delete from users where Id = #{id}")
    void deleteById(String id);

    @Update("SET foreign_key_checks = 0")
    void closeForeignKey();
    @Update("SET foreign_key_checks = 1")
    void openForeignKey();

}
